<template lang="pug">
  .clearfix
    Modal(
      width="720"
      v-model="isShowExportPDFModal"
      title="生成付款单"
      class-name="vertical-center-modal"
    )
      .search-form
        Form.ivu-row.has-rules-item2(ref="formData" :model="formData" :rules="rules" :label-width="160")
          FormItem.form-item.ivu-col.pr-20(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
            template(v-if="item.type === 'input'")
              Input(v-model="formData[item.model]" :placeholder="item.placeholder" :disabled="item.isDisabled" :type="item.model == 'amt' ? 'number' : 'text'")
            template(v-if="item.type === 'select'")
              Select(v-if="item.fn" v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable :disabled="item.isDisabled" @on-change="(event, type) => listenCall(item.fn, item.model, event)")
                Option(v-for="(c_item, c_index) in arrListDown[item.options]" :value="c_item.value" :key="c_index" ) {{ c_item.label }}
              Select(v-else v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable :disabled="item.isDisabled")
                Option(v-for="(c_item, c_index) in arrListDown[item.options]" :value="item.model == 'payType' ? c_item.label : c_item.value" :key="c_index" ) {{ c_item.label }}
            template(v-if="item.type === 'datePicker'")
              DatePicker.w-100(v-model="formData[item.model]" placeholder="请选择" type="month" format="yyyy-MM")
            template(v-if="item.type === 'upload'")
              Upload.pull-left.mb-5(
                ref="upload"
                :show-upload-list="false"
                accept=".doc, .docx, .xls, .xlsx, .pptx, .jpg, .jpeg, .png, .rar"
                :action="baseUrl + 'api/FinanceSSPayable/AnnexUpload?categoryName=商保生成付款单'"
                :on-success="uploadSuccess"
                :headers="headers"
                :max-size="10 * 1024"
                :on-exceeded-size="handleMaxSizeTen"
              )
                Button.download-btn(type="info") 附件上传
              div.pull-left.line-h-32.ml-10(v-if="fileObj && fileObj.Id")
                span.mr-10 {{fileObj.Name}}
                Icon.cursor-pointer.text-error(type="ios-close-circle" @click="removeFile")

      .clearfix(slot="footer")
        Button(type="text" @click="cancel") 取消
        Button(type="primary" @click="handleSubmit" :loading="!isCanSubmit") 确定
</template>

<script>
import { FinanceCPayableApi } from '@/api/FinanceCPayable.api.js'
import { Common } from '@/utils/common.js'
import Cookies from 'js-cookie'
import config from '@/config'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro.replace('/api', '/')
export default {
  name: '',

  props: {
  },

  computed: {
  },

  components: {
  },

  data () {
    const validateAmt = (rule, value, callback) => {
      // if (value > this.parentAmt) {
      //   callback(new Error('金额不能大于'+this.parentAmt))
      // } else {
      //   callback()
      // }
      if (value <= 0) {
        callback(new Error('金额不能为0和负数'))
      } else {
        callback()
      }
    }

    return {
      headers: {
        'Authorization': 'Bearer ' + Cookies.get('clientToken')
      },
      baseUrl: baseUrl,
      isShowExportPDFModal: false,
      formData: {
        feeDate: null,
        commercialID: null,
        commercialNo: null,
        unitName: null,
        unitNameStr: null,
        bankName: null,
        accountNo: null,
        payType: null,
        amt: null,
        remark: null,
        annexId: null
      },
      formItem: [
        { type: 'input', label: '费用月份：', placeholder: '请选择费用月份', prop: 'feeDate', model: 'feeDate', style: 'ivu-col-span-12', isDisabled: true },
        { type: 'input', label: '商保编号：', placeholder: '请选择商保编号', prop: 'commercialNo', model: 'commercialNo', style: 'ivu-col-span-12', options: 'securityNos', isDisabled: true },
        { type: 'select', label: '收款单位：', placeholder: '请选择收款单位', prop: 'unitName', model: 'unitName', style: 'ivu-col-span-24', options: 'payAccount', fn: 'unitNameChange' },
        { type: 'input', label: '开户行：', placeholder: '请输入开户行', prop: 'bankName', model: 'bankName', style: 'ivu-col-span-24', isDisabled: true },
        { type: 'input', label: '收款账号：', placeholder: '请输入收款账号', prop: 'accountNo', model: 'accountNo', style: 'ivu-col-span-12', isDisabled: true },
        { type: 'select', label: '付款方式：', placeholder: '请选择付款方式', prop: 'payType', model: 'payType', style: 'ivu-col-span-12', options: 'PayType' },
        { type: 'input', label: '金额（人民币）：', placeholder: '请输入金额（人民币）', prop: 'amt', model: 'amt', style: 'ivu-col-span-12' },
        { type: 'input', label: '付款说明：', placeholder: '请输入付款说明', prop: 'remark', model: 'remark', style: 'ivu-col-span-12' },
        { type: 'upload', label: '附件上传：', placeholder: '附件上传', prop: 'annexId', model: 'annexId', style: 'ivu-col-span-24' },
      ],
      rules: {
        unitName: [
          { required: true, message: '请选择收款单位' }
        ],
        // bankName: [
        //   { required: true, message: '请输入开户行' }
        // ],
        payType: [
          { required: true, message: '请选择付款方式' }
        ],
        amt: [
          { required: true, message: '请输入金额' },
          // { validator: validateAmt, trigger: 'blur' }
        ],
        remark: [
          { required: true, message: '请输入付款说明' }
        ],
      },
      arrListDown: {
        // securityNos: [],
        // payType: []
      },
      isCanSubmit: true,
      parentAmt: 0,
      fileObj: null,
    }
  },

  watch: {
  },

  mounted () {
  },

  methods: {
    // 监听所有调用的方法
    listenCall (methodsWords, ...values) {
      this[methodsWords](...values)
    },

    cancel () {
      this.isShowExportPDFModal = false
    },

    show (row, amt) {
      this.$refs.formData.resetFields()
      this.isCanSubmit = true
      this.isShowExportPDFModal = true
      this.fileObj = null
      if (row) {
        var month = row.periodMonth > 10 ? row.periodMonth : '0' + row.periodMonth
        this.formData.feeDate = row.periodYear + '-' + month
        this.formData.year = row.periodYear
        this.formData.month = row.periodMonth
        this.formData.commercialNo = row.commercialNo
        this.formData.commercialID = row.commercialID
      }
      this.formData.amt = amt
      this.formData.payType = this.arrListDown.PayType ? this.arrListDown.PayType[0].label : '转账'
      this.parentAmt = amt
    },

    // 收款单位改变
    unitNameChange (model, value) {
      console.log('收款单位改变 model: ', model, ', value: ', value)
      var selectedUnit = this.arrListDown.payAccount.find(item => {return item.value == value})
      console.log('selectedUnit: ', selectedUnit)
      this.formData.bankName = selectedUnit.bankName
      this.formData.accountNo = selectedUnit.accountNo
      this.formData.unitNameStr = selectedUnit.label
    },
    
    handleSubmit () {
      this.$emit('handleShowChooseTypeModal') // 临时看效果
      console.log('this.formData: ', this.formData)
      this.isCanSubmit = false
      this.$refs.formData.validate((valid) => {
        if (valid) {
          console.log('ok')
          FinanceCPayableApi.applyPay({
            ...this.formData,
            SecurityNo: this.formData.commercialNo,
            commercialID: this.formData.commercialID,
            unitName: this.formData.unitNameStr
          }).then(res => {
            if (res.status === 200 && res.data.success) {
              console.log('❤ 返回链接: ', baseUrl + res.data.message)
              window.open(baseUrl + res.data.message, '_blank')
              this.$emit('query')
            } else {
              this.$Message.error({
                content: res.data.message,
                duration: 10,
                closable: true
              })
            }
          })
          this.isShowExportPDFModal = false
        } else {
          this.isCanSubmit = true
        }
      })
    },

    // 上传前文件
    handleBeforeUpload (file) {
      var str = file.name.substring(file.name.lastIndexOf('.'), file.name.length)
      if (['.xls', '.xlsx'].indexOf(str) == -1) {
        this.$Message.warning('仅支持上传xlsx文件')
        this.file = null
      } else {
        this.file = file
        console.log('file: ', this.file)
      }
      return false
    },

    // 上传成功
    uploadSuccess (res, row) {
      console.log('上传成功res: ', res)
      console.log('上传成功row: ', row)
      if (res.Code === 200 && res.Success) {
        this.fileObj = res.Data
        this.formData.annexId = res.Data.Id
      } else {
        this.$Message.error({
          content: res.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 普通附件下载
    accessoryDownload (url) {
      console.log('下载url: ', url)
      window.open(url, '_blank')
    },

    // 移除附件
    removeFile () {
      this.fileObj = null
      this.formData.annexId = null
    },

    // 超过10M提示
    handleMaxSizeTen () {
      this.$Message.error({
        content: '您上传的文件太大，上传文件大小不能超过10M',
        duration: 10,
        closable: true
      })
    }
  }
}
</script>

<style lang="less" scope>
</style>
